#!/bin/bash
# An utitlity to create a virutal host for apache
# Author: "A. K. M. Mokaddim"<shiplu@mokadd.im>
#

# Administrator email address 
ADMIN_MAIL=admin@domain.com

# Directory where all the virtual hosts are kept
VHOST_DIR=/srv/sites

# Error log directory
ERR_LOG_DIR=/var/log/apache2

# Custom log directory
CUS_LOG_DIR=/var/log/apache2

if [[ "$1" = "" ]]
then
        # no site name given. prompt for one.
        echo Enter a name for the site
        read name
        if [[ "$name" = "" ]]
        then
                echo No name given. Site can not be created.
                exit
        else
                SITE=$name
        fi
elif [[ "$1" = "--help" ]]
then
        # show a help
        echo $0 SITE_NAME
        exit
else
        SITE=$1
fi

# entry for apache virtual host file
ENTRY=$(cat <<FINISH
<VirtualHost *:80>
        ServerAdmin ${ADMIN_MAIL}
        DocumentRoot "${VHOST_DIR}/${SITE}"
        ErrorLog ${ERR_LOG_DIR}/${SITE}.error.log
        CustomLog ${CUS_LOG_DIR}/${SITE}.access.log common
        ServerName $SITE
        ServerAlias www.$SITE
        <Directory "${VHOST_DIR}/${SITE}">
                AllowOverride All
        </Directory>
</VirtualHost>
FINISH
)

# create necessary directories
if [[ ! -e "${VHOST_DIR}/${SITE}" ]]
then
        mkdir "${VHOST_DIR}/${SITE}"
fi

# writing to hosts entry so that they fall back to localhost
sh -c "echo 127.0.0.1 $SITE >> /etc/hosts"

# create the site entry for apache virtual host
sh -c "echo '$ENTRY' > /etc/apache2/sites-available/$SITE"

# Enabling the site
a2ensite $SITE

# Restarting apache
apache2ctl restart
